package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description TODO
 * @Author dingchunlin
 * @Date 2023/8/20 15:55
 * @Version 1.0.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public Orders submit(OrdersSubmitDTO dto) {
        //首先获取当前用户的id
        Long userId = BaseContext.getCurrentId();
        //处理各种业务异常（地址簿为空或者购物车为空）
        AddressBook addressBook = addressBookMapper.selectById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //将当前下单的商品查询出来，也就是查询购物车中的数据
        List<ShoppingCart> list = shoppingCartMapper.list(userId);
        if ( list==null || list.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        Orders orders = new Orders();
        //将前端传递进来的参数拷贝到Order对象中
        BeanUtils.copyProperties(dto, orders);
        //随机生成订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //将订单状态设为未付款
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        // TODO 这个用户名没有获取
        // orders.setUserName(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        if (orders.getRemark() == null || orders.getRemark() ==""){
            orders.setRemark("无");
        }
        //这个是将订单添加到订单表中
        orderMapper.saveOrder(orders);
        //将订单表和订单详细表关联起来
        Long orderId = orders.getId();
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail,new String("id"));
            orderDetail.setOrderId(orderId);
            orderMapper.saveOrderDetail(orderDetail);
        }
        //下单之后是否需要将购物车的数据进行删除
        shoppingCartMapper.clean(userId);
        return orders;
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //创建一个返回类型
        PageResult result = new PageResult();
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //将当前用户id进行保存
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> orderPage = orderMapper.orderByPage(ordersPageQueryDTO);
        //创建一个返回类型
        List<OrderVO> orderVOS = new ArrayList<>();
        //获取分页的结果
        List<Orders> ordersList = orderPage.getResult();
        //首先将结果进行遍历获取到order的数据，然后根据订单id获取订单的详细信息
        String name = "";
        for (Orders orders : ordersList) {
            OrderVO dto = new OrderVO();
            BeanUtils.copyProperties(orders,dto);
            List<OrderDetail> orderDetailList = orderMapper.getOrderDetailList(orders.getId());
            //设置菜品的信息
            int num = 0;
            for (OrderDetail orderDetail : orderDetailList) {
                num++;
                if (num == 1) {
                    name = orderDetail.getName() + "x" + orderDetail.getNumber();
                }else {
                    name = name + "," +orderDetail.getName() + "x" + orderDetail.getNumber();
                }
            }
            dto.setOrderDetailList(orderDetailList);
            dto.setOrderDishes(name);
            orderVOS.add(dto);
        }
        result.setTotal(orderPage.getTotal());
        result.setRecords(orderVOS);
        return result;
    }

    @Override
    public OrderVO orderDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.selectByid(id);
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetailList = orderMapper.getOrderDetailList(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void repetition(Long id) {
        //根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderMapper.getOrderDetailList(id);
        //循环遍历订单详情中的数据，获得每个商品
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            //将属性进行拷贝，除了订单详情的id不拷贝
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            //设置购物车的user_id
            shoppingCart.setUserId(BaseContext.getCurrentId());
            //设置添加购物车的时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            //将数据添加到购物车数据中
            shoppingCartMapper.save(shoppingCart);
        }

    }

    @Override
    public OrderStatisticsVO statistics() {
        return orderMapper.statistics();
    }

    @Override
    public void updateOrders(Orders orders) {
        orderMapper.updateOrders(orders);
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getByUserId(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    @Override
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.selectByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.updateOrders(orders);
        //通过websocket向客户端浏览器推送消息

        Map map = new HashMap();
        map.put("type",1);//1:表示来单提醒 2:表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+ordersDB.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public void reminder(Long id) {
        //通过订单id查询订单信息
        Orders orders = orderMapper.selectByid(id);
        //通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type",2);//1:表示来单提醒 2:表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
